package com.xpchenfrank.interceptor;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Properties;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author xpchen
 * @time 2018/4/12 14:12
 * @Description
 * @copyright Wuxi Yazuo ,Ltd.copyright 2015-2025
 */
@Intercepts({ @Signature(type = Executor.class, method = "update",
        args = { MappedStatement.class, Object.class }) })
public class CommonDbInterceptor implements Interceptor {

    private Logger logger = LoggerFactory.getLogger(getClass());
    private final static String FIELD_ID = "id";
    private final static String FIELD_GMT_CREATE = "created";
    private final static String FIELD_GMT_MODIFIED = "lastupdated";

    @SuppressWarnings({ "rawtypes" })
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        try {
            Object parameter = invocation.getArgs()[1];
            LocalDateTime now = LocalDateTime.now();
            Class classParameter = (Class) parameter.getClass();
            Field[] fields = classParameter.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                String fieldName = field.getName();
                if (FIELD_GMT_CREATE.equalsIgnoreCase(fieldName)) {
                    Object value = field.get(parameter);
                    if (value == null) {
                        // created只有插入才添加
                        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
                        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
                        if (SqlCommandType.INSERT.equals(sqlCommandType)) {
                            field.set(parameter, now);
                        }
                    }
                } else if (FIELD_GMT_MODIFIED.equalsIgnoreCase(fieldName)) {
                    field.set(parameter, now);
                }
            }
        } catch (Exception e) {
            logger.error("通用设置值时出错", e);
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }

}
